<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle" @click="gotoUrl(obj)"></div>

        <!-- 筛选弹窗 -->
        <!-- <el-dialog width="550px" title="查询数据" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
            append-to-body>
            <el-form ref="formRef" class="dialog-from-margin" :rules="rules" status-icon :model="filterForm"
                label-position="left" label-width="60px">
                <el-form-item label="类型：" prop="sortType">
                    <el-radio v-model="filterForm.sortType" label="1">最新</el-radio>
                    <el-radio v-model="filterForm.sortType" label="2">历史</el-radio>
                </el-form-item>
                <el-form-item label="范围：" prop="dateTime" v-if="filterForm.sortType == 2">
                    <el-date-picker size="small" v-model="filterForm.dateTime" type="daterange"
                        value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="filterData()">确定</el-button>
            </div>
        </el-dialog> -->
    </div>
</template>

<script>
import * as echarts from 'echarts';

// import { cardDataLoad, boardLoad } from '@/api/share'
import moment from "moment"

var defaultData = ['分类1', '分类2', '分类3', '分类4'];
var defaultItem = ['系列1', "系列2", '系列3'];
var defaultValue = [
    [80, 99, 121, 266],
    [150, 180, 211, 177],
    [66, 280, 311, 553],
]

export default {
    Name: "Scatter",
    components: {
        echarts
    },
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        gotoUrl: Function,
    },
    data() {
        // var checkDatetime = (rule, value, callback) => {
        //     if (this.filterForm.sortType == "2" && !value) {
        //         callback(new Error("请选择时间范围"));
        //     } else {
        //         callback();
        //     }
        // };

        return {
            showContent: false,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 获取图标数据
            filterForm: {
                pageInfo: {
                    pageSize: 999,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
            // rules: { dateTime: [{ validator: checkDatetime, trigger: "blur" }], },
            // 用于比对数据是否修改
            dataStr: "",
            dialogFormVisible: false,
            timer: null,
            // echart数据对象
            xData: [],  //x轴数据列表
            yColumns: [],  // y轴名称列表
            serverData: [], // 数据对象列表
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        reloadInfo() {
            // 重绘
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);
            clearInterval(this.timer);

            const end = new Date();
            const start = new Date();
            // #*********# 硬件表不读取缓存 / 非硬件表默认读取缓存
            // 缓存读取数据
            if (this.obj.tableData.type != 1) {
                this.filterForm.isOnlie = true;

                // 查询一天内数据
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                this.filterForm.beginTime = this.parseTime(start);
                this.filterForm.endTime = this.parseTime(end);
            } else {
                this.filterForm.isOnlie = false;

                start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d}");
                this.filterForm.endTime = this.parseTime(end);
            }

            this.getLineData((dataResult) => {
                var data = this.resultDataToObject(dataResult);
                this.setOptions(data.xData, data.yColumns, data.serverData);

                // 循环刷新
                this.timedRefresh();
            });
        },
        // 数据转换
        resultDataToObject(dataResult) {
            var xData = [];
            var serveData = [];
            var columns = [];

            dataResult.columns.forEach((x, j) => {
                if (j > 0) {
                    columns.push(x.name)
                }
            })

            for (var i = 0; i < dataResult.dataList[0].length; i++) {
                var data = [];
                dataResult.dataList.forEach((x, j) => {
                    data.push(x[i]);
                });
                if (i == 0) {
                    xData = data;
                } else {
                    serveData.push(data);
                }
            }

            return {
                xData: xData,
                yColumns: columns,
                serverData: serveData,
            }
        },
        // 定时刷新
        timedRefresh() {
            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            // 刷新时间兼容处理
            if (this.obj.tableData.type == 1 && timeSize < 60) {
                timeSize = 60;
            }

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end);

                    this.getLineData((dataResult) => {
                        var data = this.resultDataToObject(dataResult);
                        this.setOptions(data.xData, data.yColumns, data.serverData);
                    });
                }, timeSize * 1000);
            }
        },
        // filterData() {
        //     this.$refs["formRef"].validate((valid) => {
        //         if (valid) {
        //             this.dialogFormVisible = false;
        //             if (this.filterForm.sortType == 1) {
        //                 this.filterForm.beginTime = undefined;
        //                 this.filterForm.endTime = undefined;
        //             } else {
        //                 this.filterForm.beginTime = this.filterForm.dateTime[0];
        //                 this.filterForm.endTime = this.filterForm.dateTime[1];
        //             }

        //             this.getLineData();
        //         }
        //     });
        // },
        setStyle() {
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";
            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
                // this.setImgInfo(style.backgroundImage)
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "";
            }

            this.carStyle = {
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions(expectedData, columns, actualData) {
            var seriesData = [];
            var self = this;

            // 颜色相关
            var color = "#333333";
            if (this.obj.tableData.color) {
                color = this.obj.tableData.color;
            }
            var lineColor = "#eeeeee"
            if (this.obj.tableData.lineColor) {
                lineColor = this.obj.tableData.lineColor;
            }

            // 设置y轴范围
            if (this.obj.tableData.isSetTranslate) {
                var minSize = 0;
                var maxSize = 100;
                if (this.obj.tableData.minSize) {
                    minSize = this.obj.tableData.minSize;
                }
                if (this.obj.tableData.maxSize) {
                    maxSize = this.obj.tableData.maxSize;
                }
            } else {
                var minSize = undefined;
                var maxSize = undefined;
            }
            // 自定义颜色
            var colors = ['#fc8251', '#5470c6', '#91cd77', '#ef6567', '#f9c956', '#75bedc'];
            var newColors = [];
            this.obj.tableData.yList.forEach(e => {
                if (e.color) {
                    newColors.push(e.color);
                }
            });
            newColors = newColors.concat(colors);

            // 散点太大设置比率
            var bl = 1;
            if (this.obj.tableData.sizeBl) {
                bl = this.obj.tableData.sizeBl;
            }

            // #region 图例 legend样式
            var isShowLegend = true;
            if (this.obj.tableData.isShowLegend != undefined) {
                isShowLegend = this.obj.tableData.isShowLegend;
            }
            var icon = "circle";
            if (this.obj.tableData.icon) {
                icon = this.obj.tableData.icon;
            }

            var textColor = "#333333";
            if (this.obj.tableData.textColor) {
                textColor = this.obj.tableData.textColor;
            }
            var textFontsize = '14px';
            if (this.obj.tableData.textfontSize) {
                textFontsize = this.obj.tableData.textfontSize + "px";
            }
            var textFontWeight = "";
            if (this.obj.tableData.textFontWeight) {
                textFontWeight = this.obj.tableData.textFontWeight;
            }
            var textFontStyle = "";
            if (this.obj.tableData.textFontStyle) {
                textFontStyle = this.obj.tableData.textFontStyle;
            }

            // #endregion

            actualData.forEach((x, i) => {
                seriesData.push({
                    // name: 'expected', 
                    // itemStyle: {
                    //     normal: {
                    //         color: '#FF005A',
                    //         lineStyle: {
                    //             color: '#FF005A',
                    //             width: 2
                    //         }
                    //     }
                    // },
                    name: columns[i],
                    smooth: false,
                    type: 'scatter',
                    data: x,
                    animationDuration: 2800,
                    animationEasing: 'cubicInOut',
                    label: {
                        show: this.obj.tableData.isShowValue,
                        formatter: function (a, b, c) {
                            if (a.value >= 0 && self.obj.tableData.decimal >= 0) {
                                return Number(a.value).toFixed(self.obj.tableData.decimal);
                            }
                            return a.value;
                        }
                    },
                    symbol: 'circle',     //设定为实心点
                    // symbolSize: 4,   //设定实心点的大小
                    symbolSize: function (data) {
                        return Math.sqrt(data * bl);
                    },
                });
            });

            this.chart.setOption({
                color: newColors,
                xAxis: {
                    data: expectedData.map(function (str) {
                        if (!isNaN(Date.parse(str)) && Date.parse(str) > 631152000000) {
                            return moment(str).format("YYYY/MM/DD") + "\n" + moment(str).format("HH:mm:ss")
                        }
                        return str;
                    }),
                    boundaryGap: false,
                    axisLine: {
                        lineStyle: {
                            color: lineColor
                        },
                    },
                    splitLine: {
                        show: this.obj.tableData.isShowGrid,
                        lineStyle: {
                            color: lineColor,
                            width: 1,
                        }
                    },
                    axisLabel: {
                        color: color
                    }
                },
                grid: {
                    left: "4%",
                    right: 40,
                    bottom: 20,
                    top: "60px",
                    containLabel: true
                },
                tooltip: {
                    // trigger: 'axis',
                    backgroundColor: "rgba(0,0,0, .7)",
                    textStyle: {
                        color: "#ffffff"
                    },
                    position: 'top',
                    formatter: function (params) {
                        return `${params.name}<br>${params.seriesName} ${params.value}`;
                    }
                },
                yAxis: {
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {
                            color: color
                        }
                    },
                    splitLine: {
                        show: this.obj.tableData.isShowGrid,
                        lineStyle: {
                            color: lineColor,
                            width: 1,
                        }
                    },
                    min: minSize,
                    max: maxSize,
                },
                legend: {
                    top: "25px",
                    left: "15px",
                    show: isShowLegend,
                    // orient: orient,
                    right: 10,
                    textStyle: {
                        color: textColor,
                        fontSize: textFontsize,
                        fontWeight: textFontWeight,
                        fontStyle: textFontStyle,
                    },
                    icon,
                    formatter: (val) => {
                        return val;
                    }
                },
                // legend: {
                //     data: columns,
                //     itemHeight: 12,
                //     itemWidth: 12,
                //     icon: 'circle',
                //     top: "25px",
                //     left: "15px",
                //     textStyle: {
                //         color: color
                //     },
                // },
                series: seriesData
            })
        },
        getLineData(callback) {
            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;

                this.setOptions(defaultData, defaultItem, defaultValue);
                return false;
            }
            // #endregion

            // #region 参数不完整
            var idlist = [this.obj.tableData.xId];
            if (this.obj.tableData.yList.length == 0) {
                this.showContent = false;
                return false;
            }
            this.obj.tableData.yList.forEach(e => {
                if (e.id) {
                    idlist.push(e.id);
                }
            });
            if (idlist.length - 1 != this.obj.tableData.yList.length) {
                this.showContent = false;
                return false;
            }
            // #endregion

            this.showContent = true;
            this.filterForm.tableId = this.obj.tableData.tableId;
            this.filterForm.pageInfo.pageSize = this.obj.tableData.count;
            this.filterForm.structureIds = idlist;

            if (this.obj.tableData.type != 1) {
                cardDataLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {

                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            } else {
                boardLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });;
            }
        },
        // 日期筛选触发查询函数
        dateSearch(beginTime, endTime) {
            clearInterval(this.timer);
            this.filterForm.beginTime = beginTime;
            this.filterForm.endTime = endTime;
            this.filterForm.isOnlie = false;

            this.getLineData((dataResult) => {
                var data = this.resultDataToObject(dataResult);
                this.setOptions(data.xData, data.yColumns, data.serverData);
            });
        },
        // setImgInfo(url) {
        //     var id = url.split('=')[1];
        //     var self = this;
        //     axios({
        //         method: "GET",
        //         url: process.env.VUE_APP_FILE_GETPATH,
        //         params: { fileid: id },
        //         timeout: 10000,
        //     }).then((res) => {
        //         if (res.data.code == 0) {
        //             if (res.data.data.path.indexOf('.gif') > 0) {
        //                 // obj.imgData = res.data.data.path;
        //                 self.carStyle.backgroundImage = `url(${res.data.data.path}`;
        //             } else {
        //                 self.image2Base64(url);
        //             }
        //         }
        //     })
        // },
        // image2Base64(url) {
        //     var self = this;
        //     var canvas = document.createElement('canvas'),
        //         ctx = canvas.getContext('2d'),
        //         img = new Image();
        //     img.crossOrigin = 'Anonymous';
        //     img.src = url;

        //     img.onload = function () {
        //         canvas.height = img.height;
        //         canvas.width = img.width;
        //         ctx.drawImage(img, 0, 0);
        //         // var dataURL = canvas.toDataURL('image/jpeg');

        //         var data = canvas.toDataURL("image/png");
        //         self.carStyle.backgroundImage = `url(${data}`;
        //     };
        // },
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>